//
//  SetPasswordViewController.m
//  LocomotiveGuards
//
//  Created by zwj on 15-11-23.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "SetPasswordViewController.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
@interface SetPasswordViewController () <UITextFieldDelegate>
{
    UILabel *_labelSetpwd;
    UILabel *_labelConfirmpwd;
    UITextField *_fieldSetpsw;
    UITextField *_fieldConfirmpsw;
    UILabel *_tipLabel;
    UILabel *_newTipLabel;
    UIButton *_btnLast;
    UIButton *_btnComplete;
    NSString *_idPicName;
    NSString *_picUrl;
    UIImage *_carImage;
    NSInteger flagRegister;
    NSInteger flagSetPwd;
}
@end

@implementation SetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addTitle:@"账号激活"];
    [self configView];
}

- (void)configView
{
    //设置密码label
    _labelSetpwd = [self createLabelFrame:CGRectMake(20*W, 140*H, SCREEN_WIDTH-40*W, 30*H) title:@"设置密码" font:[UIFont systemFontOfSize:26]];
    [self.view addSubview:_labelSetpwd];
    
    //设置密码输入框
    _fieldSetpsw = [self createTextFieldFrame:CGRectMake(20*W, CGRectGetMaxY(_labelSetpwd.frame)+20*H, SCREEN_WIDTH-40*W, 35*H) title:nil placeholder:@"6-12位字母或数字"];
    _fieldSetpsw.returnKeyType = UIReturnKeyDone;
    _fieldSetpsw.secureTextEntry = YES;
    _fieldSetpsw.delegate = self;
    [self.view addSubview:_fieldSetpsw];
    
    //设置密码提示
    _tipLabel = [self createLabelFrame:CGRectMake(20*W, CGRectGetMaxY(_fieldSetpsw.frame)+15*H, SCREEN_WIDTH-40*W, 15*H) title:@"" font:[UIFont systemFontOfSize:15]];
    _tipLabel.textColor = [UIColor cyanColor];
    [self.view addSubview:_tipLabel];
    _tipLabel.hidden = YES;
    
    //确认密码label
    _labelConfirmpwd = [self createLabelFrame:CGRectMake(20*W, CGRectGetMaxY(_tipLabel.frame)+20*H, SCREEN_WIDTH-40*W, 30*H) title:@"确认密码" font:[UIFont systemFontOfSize:26]];
    [self.view addSubview:_labelConfirmpwd];
    
    //确认密码输入框
    _fieldConfirmpsw = [self createTextFieldFrame:CGRectMake(20*W, CGRectGetMaxY(_labelConfirmpwd.frame)+20*H, SCREEN_WIDTH-40*W, 35*H) title:nil placeholder:@"确认密码"];
    _fieldConfirmpsw.delegate = self;
    _fieldConfirmpsw.returnKeyType = UIReturnKeyDone;
    _fieldConfirmpsw.secureTextEntry = YES;
    [self.view addSubview:_fieldConfirmpsw];
    
    //确认密码提示
    _newTipLabel = [self createLabelFrame:CGRectMake(20*W, CGRectGetMaxY(_fieldConfirmpsw.frame)+15*H, SCREEN_WIDTH-40*W, 15*H) title:@"" font:[UIFont systemFontOfSize:15]];
    _newTipLabel.textColor = [UIColor cyanColor];
    [self.view addSubview:_newTipLabel];
    _newTipLabel.hidden = YES;
    
    //上一步按钮
    _btnLast = [self addLastBtnTarget:self action:@selector(btnLastClicked:)];
    [self enableButton:_btnLast];
    
    //下一步按钮
    _btnComplete = [self addNextBtnTarget:self action:@selector(btnCompleteClicked:)];
    [self disableButton:_btnComplete];
    [_btnComplete setTitle:@"完成" forState:UIControlStateNormal];
    [self disableButton:_btnComplete];
}

#pragma mark - 网络请求
//上传车辆照片网络请求
- (void)uploadCarPicRequest
{
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];
    
    NSData *carPicData = UIImageJPEGRepresentation(_carImage, 0.5);
    
    
    
#warning  测试省市区三级联动的时候进行操作
    NSString *phoneNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNo"];
    
    
//    phoneNumber =  @"13764807768";
    
    NSDictionary *paramdic = @{@"loginId":phoneNumber};
    NSString *url = [urlstring stringByAppendingString:@"uploadEbicyclePic.do"];
    
    [K_AppDelegate UploadHTTPRequestWithUrl:url withParam:paramdic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:carPicData name:@"ebicyclePic" fileName:@"file" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        _picUrl = [dic objectForKey:@"picUrl"];
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
        if (flag == 0) {
            //上传成功
            NSLog(@"车辆照片上传成功->picUrl = %@",_picUrl);
            [self uploadIdCardPicRequest];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}

//上传身份证照片网络请求
- (void)uploadIdCardPicRequest
{
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];
    
    NSString *idPicPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"idcardPic.png"];
    NSLog(@"%@",idPicPath);
    UIImage *saveImage = [[UIImage alloc] initWithContentsOfFile:idPicPath];
    NSData *idPicData = UIImageJPEGRepresentation(saveImage, 0.5);

    
    
#warning 注册省市区三级联动的时候进行修改操作
    NSString *phoneNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNo"];
    
//  phoneNumber = @"13764807768";
    
    
    
    NSDictionary *paramdic = @{@"loginId":phoneNumber};
    NSString *url = [urlstring stringByAppendingString:@"uploadIdcardPic.do"];

    [K_AppDelegate UploadHTTPRequestWithUrl:url withParam:paramdic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:idPicData name:@"idcardPic" fileName:@"file" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        _idPicName = [dic objectForKey:@"picName"];
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
        if (flag == 0) {
            //上传成功再调注册接口
            NSLog(@"身份证照片上传成功");
            [self registerRequest];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}


//注册接口请求
- (void)registerRequest
{
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];
    
    NSString *phoneNum = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNo"];
    
//    phoneNum = @"13764807768";
    
    
    NSDictionary *paramdic = @{@"loginId":phoneNum,
                               @"verifyCode":[[NSUserDefaults standardUserDefaults] objectForKey:@"verifyCode"],
                               @"idcardNum":[[NSUserDefaults standardUserDefaults] objectForKey:@"idcardNum"],
                               @"idcardPic":_idPicName,
                               @"name":[[NSUserDefaults standardUserDefaults] objectForKey:@"personName"],
                               @"province":[[NSUserDefaults standardUserDefaults] objectForKey:@"provinceName"],
                               @"city":[[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"],
                               @"district":[[NSUserDefaults standardUserDefaults] objectForKey:@"districtName"],
                               @"detailAdress":[[NSUserDefaults standardUserDefaults] objectForKey:@"detailAdd"],
                               @"simId":[[NSUserDefaults standardUserDefaults] objectForKey:@"simId"],
                               @"brand":[[NSUserDefaults standardUserDefaults] objectForKey:@"brandName"],
                               @"ebicyclePic":_picUrl,
                               @"buyTime":[[NSUserDefaults standardUserDefaults] objectForKey:@"buyTime"],
                               @"frameId":[[NSUserDefaults standardUserDefaults] objectForKey:@"frameId"],
                               @"pwd":[[NSUserDefaults standardUserDefaults] objectForKey:@"password"]
                               };
    
    
    
    NSString *url = [urlstring stringByAppendingString:@"register.do"];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        
        flagRegister = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
        NSLog(@"flagRegister = %i", flagRegister);
        [self verifyRegister];
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}

//设置密码请求
- (void)setPwdRequest
{
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];
    
    NSDictionary *paramdic = @{@"loginId":[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNo"],
                               @"loginPwd":[[NSUserDefaults standardUserDefaults] objectForKey:@"password"]};
    NSString *url = [urlstring stringByAppendingString:@"setPwd.do"];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        
        flagSetPwd = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
        NSLog(@"flagSetPwd = %i", flagSetPwd);
        [self verifySetPwd];
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}

#pragma mark - 点击事件
//上一步，返回上一个页面(从哪来回哪去)
- (void)btnLastClicked:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//点击完成按钮，进行网络请求
- (void)btnCompleteClicked:(id)sender
{
    int i = [self checkIsHaveNumAndLetter:_fieldSetpsw.text];
    
    if(![_fieldConfirmpsw.text isEqualToString:_fieldSetpsw.text]){
        _newTipLabel.text = @"※两次密码输入不一致,请重新输入";
        _newTipLabel.hidden = NO;
        if(_fieldSetpsw.text.length < 6){
            _tipLabel.font = [UIFont systemFontOfSize:15];
            _tipLabel.text = @"※密码低于6位,请重新输入";
            _tipLabel.hidden = NO;
        }
        else if(_fieldSetpsw.text.length > 12){
            _tipLabel.font = [UIFont systemFontOfSize:15];
            _tipLabel.text = @"※密码高于12位,请重新输入";
            _tipLabel.hidden = NO;
        }
        else if(i==0){
            _tipLabel.font = [UIFont systemFontOfSize:14];
            _tipLabel.text = @"※密码必须包括大小写字母和数字,请重新输入";
            _tipLabel.hidden = NO;
        }
        else {
            _tipLabel.hidden = YES;
        }
    }
    else {
        _newTipLabel.hidden = YES;
        if(_fieldSetpsw.text.length < 6){
            _tipLabel.font = [UIFont systemFontOfSize:15];
            _tipLabel.text = @"※密码低于6位,请重新输入";
            _tipLabel.hidden = NO;
        }
        else if(_fieldSetpsw.text.length > 12){
            _tipLabel.font = [UIFont systemFontOfSize:15];
            _tipLabel.text = @"※密码高于12位,请重新输入";
            _tipLabel.hidden = NO;
        }
        else if(i==0){
            _tipLabel.font = [UIFont systemFontOfSize:14];
            _tipLabel.text = @"※密码必须包括大小写字母和数字,请重新输入";
            _tipLabel.hidden = NO;
        }
        else {
            _tipLabel.hidden = YES;
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:_fieldConfirmpsw.text forKey:@"password"];
            //激活账号流程
            if (self.flag == 1) {
                //直接向服务器发送设置密码接口进行激活
                [self setPwdRequest];
            }
            //注册流程
            else if (self.flag == 3) {
                /***先调上传照片接口，再向服务器发送注册接口，再调设置密码接口***/
                NSString *carPicPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"ebicyclePic.png"];
                NSLog(@"%@",carPicPath);
                _carImage = [[UIImage alloc] initWithContentsOfFile:carPicPath];
                if (_carImage) {
                    [self uploadCarPicRequest];
                }
                else {
                    _picUrl = @"";
                    [self uploadIdCardPicRequest];
                }
            }
        }
    }
}

//根据服务器返回的值做判断
- (void)verifyRegister
{
    if (flagRegister == 0) {
        _newTipLabel.hidden = YES;

        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"phoneNo"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"verifyCode"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"idcardNum"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"personName"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"provinceName"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"cityName"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"districtName"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"detailAdd"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"simId"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"brandName"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"buyTime"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"frameId"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"password"];
        
        NSFileManager * fileManager = [NSFileManager defaultManager];
        NSString *idCardPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"idcardPic.png"];
        [fileManager removeItemAtPath:idCardPath error:nil];
        
        NSString *ebicyclePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"ebicyclePic.png"];
        [fileManager removeItemAtPath:ebicyclePath error:nil];
        
        [PopMsg showMessage:@"注册成功" Lasttime:1.0f];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else if (flagRegister == -1) {
        _newTipLabel.text = @"※该用户非APP用户,拒绝修改";
        _newTipLabel.hidden = NO;
    }
    else if (flagRegister == -2) {
        _newTipLabel.text = @"※短信验证码错误";
        _newTipLabel.hidden = NO;
    }
    else if (flagRegister == -3) {
        _newTipLabel.text = @"※短信验证码过期";
        _newTipLabel.hidden = NO;
    }
}

//根据服务器返回的值做判断
- (void)verifySetPwd
{
    if (flagSetPwd == 0) {
        _newTipLabel.hidden = YES;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"操作已成功！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [alert show];
        
    }
    else if (flagSetPwd == -1) {
        _newTipLabel.text = @"※该用户非APP用户,拒绝修改";
        _newTipLabel.hidden = NO;
    }
    else if (flagSetPwd == -2) {
        _newTipLabel.text = @"※短信验证码错误";
        _newTipLabel.hidden = NO;
    }
    else if (flagSetPwd == -3) {
        _newTipLabel.text = @"※短信验证码过期";
        _newTipLabel.hidden = NO;
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"phoneNo"];
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"password"];
    [self dismissViewControllerAnimated:YES completion:nil];
}

//收起键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_fieldSetpsw resignFirstResponder];
    [_fieldConfirmpsw resignFirstResponder];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if(_fieldSetpsw.text.length!=0 && _fieldConfirmpsw.text.length!=0 && _fieldSetpsw!=nil && _fieldConfirmpsw!=nil){
        [self enableButton:_btnComplete];
    }
    else{
        [self disableButton:_btnComplete];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_fieldSetpsw resignFirstResponder];
    [_fieldConfirmpsw resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    BOOL canChange = [string isEqualToString:filtered];
    
    return canChange;
}

- (int)checkIsHaveNumAndLetter:(NSString*)pPassword{
    //數字條件
    NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合數字條件的有幾個字元
    int tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:pPassword
                                                                options:NSMatchingReportProgress
                                                                  range:NSMakeRange(0, pPassword.length)];
    
    //大写字母條件
    NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Z]" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    
    //符合大写字母條件的有幾個字元
    int tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:pPassword options:NSMatchingReportProgress range:NSMakeRange(0, pPassword.length)];
    
    
    //小写字母條件
    NSRegularExpression *littleLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[a-z]" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    
    //符合小写字母條件的有幾個字元
    int littleLetterMatchCount = [littleLetterRegularExpression numberOfMatchesInString:pPassword options:NSMatchingReportProgress range:NSMakeRange(0, pPassword.length)];
    
    
    if (tNumMatchCount == pPassword.length)
    {
        //全部符合數字，表示沒有英文
        return 0;
    }
    else if (tLetterMatchCount == pPassword.length)
    {
        //全部符合大写字母，表示沒有數字
        return 0;
    }
    else if(littleLetterMatchCount==pPassword.length){
        //全部符合小写字母，表示沒有數字
        return 0;
    }
    else if (tNumMatchCount + tLetterMatchCount == pPassword.length)
    {
        //数字和大写字母相加为密码长度，表示没有小写字母
        return 0;
    }
    else if (tNumMatchCount + littleLetterMatchCount == pPassword.length)
    {
        //数字和小写字母相加为密码长度，表示没有大写字母
        return 0;
    }
    else if (littleLetterMatchCount + tLetterMatchCount == pPassword.length)
    {
        //小写字母和大写字母相加为密码长度，表示没有数字
        return 0;
    }
    else
    {
        return 1;
        //可能包含標點符號的情況，或是包含非英文的文字，這裡再依照需求詳細判斷想呈現的錯誤
    }
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
